//
//  KakaMessageViewController.swift
//  NewsItem
//
//  Created by mac on 2023/6/30.
//  Copyright © 2023 Kaka. All rights reserved.
//

import UIKit


class TEA_MessageViewController: BasicViewController,PixelWorldChatProtocol,NaviBarHidden {

    let topI = UIImageView.initImgView(img: "titttle_my pet1")
    private lazy var table: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.backgroundColor = .white
        view.delegate = self
        view.dataSource = self
        view.showsVerticalScrollIndicator = false
        view.register(MessageListCell.self, forCellReuseIdentifier: MessageListCell.description())
        view.rowHeight = 100.Fit
        return view
    }()
    private var messages: [PixelWorldChatMessageBodyModel] = []
    private var historyMessages: [[PixelWorldChatMessageBodyModel]] = []
    var userModelArr:[InfoUtil.initInfo] = []

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.refreshList()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        view.setGrandient(color:.topToBottom(colors:[.color(hexString: "#001F13"),.color(hexString: "#001F13")]))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.subviews {
            topI
            table
        }
        
        topI.width(345.Fit).height(60.Fit).top(status_bar_height() + 15.Fit)
        topI.centerHorizontally()
        table.left(0).right(0).bottom(0)
        table.Top == topI.Bottom + 28.Fit
        table.layer.maskedCorners = [.layerMaxXMinYCorner,.layerMinXMinYCorner]
        table.layer.cornerRadius = 25.Fit
        chat.conversationList { result in
            self.refreshList()
        }
        self.refreshList()
        table.emptyGameView(.noMessage)

    }
    
    @objc func refreshList() -> Void {
        
        let blackUserIDs = ""
        let models = self.chat.allConversations().messageModels
        self.messages = models.filter({ !blackUserIDs.contains($0.userID) })
        // 获取历史消息
        self.historyMessages.removeAll()
        self.messages.forEach { model in
            let historys = chat.historyMessages(model.easeUserID)
            self.historyMessages.append(historys)
        }
        RT.blockListWith { response in
            for data in response.users
            {
                self.messages.removeAll(where: {$0.userID == data.id})
            }
            let userIds = self.messages.map({ $0.userID })
            if !userIds.isEmpty {
                self.getUserContent(userIds)
            }
            self.table.reloadData()
         }
//        guard let model = self.messages.first else { return}
//        for _ in 0..<25{
//            self.messages.append(model)
//        }
//        self.table.reloadData()
    }
    
    private func getUserContent(_ userID: [String]) {
        userModelArr.removeAll()
        for uid in userID {
            RT.getOtherUserInfoUrlInfoWith(userid: uid) { jsonData in
                self.userModelArr.append(jsonData)
                self.table.reloadData()
            }
        }
    }

}

extension TEA_MessageViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MessageListCell.description()) as! MessageListCell
        cell.messageModel = self.messages[indexPath.row]
        if indexPath.row < self.userModelArr.count {
            self.userModelArr.forEach { info in
                if self.messages[indexPath.row].easeUserID == info.id{
                    if let str = info.headImage, let url = URL(string: str) {
                        cell.headImg.kf.setImage(with: url,placeholder: UIImage.init(named: "avarB"))
                    }
                    cell.nameL.text = info.name
                }
            }
        }
        return cell
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messages.count
    }
        
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = TEA_ChatViewController()
        vc.targetId = self.messages[indexPath.row].easeUserID
        ChatCache.cleanUnReadMessages(self.messages[indexPath.row].easeUserID)
        self.navigationController?.pushViewController(vc, animated: true)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "refreshBadge"), object: nil, userInfo:nil)
        tableView.reloadData()
    }
        
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let deleteAction = UIContextualAction(style: .normal, title: "") { [weak self] context, view, handler in
            let model = self?.messages[indexPath.row]
            self?.chat.deleteConversation(model?.easeUserID ?? "0")
            handler(true)
        }
        deleteAction.backgroundColor = .color(hexString: "#F8FAF8")
        deleteAction.image = UIImage(named: "delete")
        let actions = UISwipeActionsConfiguration(actions: [deleteAction])
        actions.performsFirstActionWithFullSwipe = false
        return actions
    }
}
    
class MessageListCell: UITableViewCell {
    
    let backV = UIView.init(frame: .zero)
    let headImg = UIImageView.initImgView(img: "avarB")
    private var cL = UILabel.initV(.setTypeFace(15,type: .medium), text: "", textColor: .color(hexString: "#666666"))
    var nameL = UILabel.initV(.setTypeFace(20,type: .bold), text: "", textColor: .black)
    
    private var timeL = UILabel.initV(.setTypeFace(14.Fit,type: .medium), text: "", textColor: .color(hexString: "#666666"))
    let deleteB = UIButton.initV(img: "")
    let numL = UILabel.initV(UIFont.setTypeFace(12,type: .medium), text: "0", textColor: .white)

    var messageModel:PixelWorldChatMessageBodyModel?{
        didSet{
            guard let model = messageModel else { return }
            self.cL.text = model.lastMessage
            self.timeL.text = model.lastTime
            self.numL.isHidden = model.unReadCount == 0
            self.numL.text = "\(model.unReadCount)"
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        backgroundColor = .clear
        selectionStyle = .none
        contentView.addSubview(backV)
        backV.addSubview(headImg)
        backV.addSubview(nameL)
        backV.addSubview(cL)
        backV.addSubview(timeL)
        backV.addSubview(numL)
        
        headImg.setAllCorners(corner: 35.Fit)
        backV.setAllCorners(corner: 14.Fit)
        backV.backgroundColor = .clear
        
        backV.snp.makeConstraints { make in
            make.top.equalTo(10.Fit)
            make.bottom.equalTo(0.Fit)
            make.leading.equalTo(15.Fit)
            make.width.equalTo(screenWidth - 30.Fit)
        }
        headImg.snp.makeConstraints { make in
            make.size.equalTo(70.Fit)
            make.leading.equalTo(15.Fit)
            make.top.equalTo(10.Fit)
        }
        timeL.textAlignment = .right
        timeL.snp.makeConstraints { make in
            make.top.equalTo(25.Fit)
            make.trailing.equalTo(-20.Fit)
            make.height.equalTo(13.Fit)
            make.width.equalTo(100.Fit)
        }
        nameL.snp.makeConstraints { make in
            make.top.equalTo(15.Fit)
            make.leading.equalTo(headImg.snp.trailing).offset(10.Fit)
            make.trailing.equalTo(timeL.snp.leading).offset(10.Fit)
            make.height.equalTo(20.Fit)
        }
        numL.backgroundColor = .red
        numL.snp.makeConstraints { make in
            make.top.equalTo(timeL.snp.bottom)
            make.trailing.equalTo(-30.Fit)
            make.size.equalTo(15.Fit)
        }
        numL.setAllCorners(corner: 7.5.Fit)
        numL.textAlignment = .center

        cL.snp.makeConstraints { make in
            make.top.equalTo(nameL.snp.bottom).offset(5.Fit)
            make.leading.equalTo(headImg.snp.trailing).offset(10.Fit)
            make.trailing.equalTo(timeL.snp.leading).offset(10.Fit)
            make.height.equalTo(20.Fit)
        }
        cL.numberOfLines = 0

        deleteB.backgroundColor = .red
        deleteB.width(40.Fit)
        deleteB.Leading == backV.Trailing
        deleteB.Top == backV.Top
        deleteB.Bottom == backV.Bottom
        deleteB.addAct {

        }
        
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
